<template>
  <div class="blog">
    <div class="container py-5">
      <!-- 页面标题 -->
      <div class="row mb-5">
        <div class="col-12 text-center">
          <h1 class="display-4 fw-bold text-primary mb-3">{{ pageInfo.title || '博客文章' }}</h1>
          <p class="lead text-muted">
            {{ pageInfo.subtitle || '分享技术心得、生活感悟和成长历程' }}
          </p>
        </div>
      </div>

      <!-- 搜索和筛选 -->
      <div class="row mb-5">
        <div class="col-lg-8 mx-auto">
          <div class="card border-0 shadow-sm">
            <div class="card-body">
              <div class="row g-3 align-items-center">
                <div class="col-md-6">
                  <div class="input-group">
                    <span class="input-group-text bg-light border-0">
                      <i class="bi bi-search"></i>
                    </span>
                    <input 
                      type="text" 
                      class="form-control border-0 bg-light" 
                      placeholder="搜索文章..."
                      v-model="searchKeyword"
                      @input="filterPosts"
                    >
                  </div>
                </div>
                <div class="col-md-3">
                  <select 
                    class="form-select border-0 bg-light" 
                    v-model="selectedCategory"
                    @change="filterPosts"
                  >
                    <option 
                      v-for="category in categories" 
                      :key="category.value" 
                      :value="category.value"
                    >
                      {{ category.name }}
                    </option>
                  </select>
                </div>
                <div class="col-md-3">
                  <select 
                    class="form-select border-0 bg-light" 
                    v-model="sortBy"
                    @change="sortPosts"
                  >
                    <option 
                      v-for="sort in sortOptions" 
                      :key="sort.value" 
                      :value="sort.value"
                    >
                      {{ sort.name }}
                    </option>
                  </select>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 文章列表 -->
      <div class="row" v-if="filteredPosts.length > 0">
        <div 
          class="col-lg-6 col-xl-4 mb-4" 
          v-for="post in paginatedPosts" 
          :key="post.id"
        >
          <article class="card h-100 border-0 shadow-sm">
            <div class="position-relative">
              <img 
                :src="getImageUrl(post.image)" 
                :alt="post.title"
                class="card-img-top"
                style="height: 200px; object-fit: cover;"
              >
              <span 
                :class="`badge position-absolute top-0 start-0 m-3 ${getCategoryColor(post.category)}`"
              >
                {{ post.category }}
              </span>
            </div>
            <div class="card-body d-flex flex-column">
              <h5 class="card-title">
                <router-link 
                  :to="`/article/${post.id}`" 
                  class="text-decoration-none text-dark"
                >
                  {{ post.title }}
                </router-link>
              </h5>
              <p class="card-text text-muted flex-grow-1">
                {{ post.excerpt }}
              </p>
              <div class="post-meta">
                <div class="d-flex justify-content-between align-items-center">
                  <small class="text-muted">
                    <i class="bi bi-calendar me-1"></i>{{ formatDate(post.date) }}
                  </small>
                  <small class="text-muted">
                    <i class="bi bi-eye me-1"></i>{{ post.views }}
                  </small>
                </div>
                <div class="mt-3">
                  <div class="d-flex justify-content-between align-items-center">
                    <div>
                      <span 
                        v-for="tag in post.tags" 
                        :key="tag"
                        class="badge bg-light text-dark me-1 mb-1"
                      >
                        #{{ tag }}
                      </span>
                    </div>
                    <router-link 
                      :to="`/article/${post.id}`" 
                      class="btn btn-outline-primary btn-sm"
                    >
                      阅读更多
                    </router-link>
                  </div>
                </div>
              </div>
            </div>
          </article>
        </div>
      </div>

      <!-- 无结果提示 -->
      <div v-else class="row">
        <div class="col-12 text-center py-5">
          <i class="bi bi-search text-muted mb-3" style="font-size: 4rem;"></i>
          <h4 class="text-muted">没有找到相关文章</h4>
          <p class="text-muted">请尝试调整搜索条件或浏览所有文章</p>
          <button @click="clearFilters" class="btn btn-primary">
            <i class="bi bi-arrow-clockwise me-2"></i>重置筛选
          </button>
        </div>
      </div>

      <!-- 分页 -->
      <div v-if="totalPages > 1" class="row mt-5">
        <div class="col-12">
          <nav aria-label="文章分页">
            <ul class="pagination justify-content-center">
              <li class="page-item" :class="{ disabled: currentPage === 1 }">
                <a class="page-link" @click.prevent="changePage(currentPage - 1)">
                  <i class="bi bi-chevron-left"></i>
                </a>
              </li>
              <li 
                class="page-item" 
                :class="{ active: page === currentPage }"
                v-for="page in visiblePages" 
                :key="page"
              >
                <a class="page-link" @click.prevent="changePage(page)">{{ page }}</a>
              </li>
              <li class="page-item" :class="{ disabled: currentPage === totalPages }">
                <a class="page-link" @click.prevent="changePage(currentPage + 1)">
                  <i class="bi bi-chevron-right"></i>
                </a>
              </li>
            </ul>
          </nav>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'Blog',
  data() {
    return {
      // 搜索和筛选状态
      searchKeyword: '',
      selectedCategory: '',
      sortBy: 'date',
      currentPage: 1,
      postsPerPage: 6,
      
      // API数据
      pageInfo: {
        title: '',
        subtitle: ''
      },
      categories: [],
      sortOptions: [],
      posts: [],
      filteredPosts: [],
      
      // 加载状态
      isLoading: true,
      apiError: null
    }
  },
  computed: {
    totalPages() {
      return Math.ceil(this.filteredPosts.length / this.postsPerPage)
    },
    paginatedPosts() {
      const start = (this.currentPage - 1) * this.postsPerPage
      const end = start + this.postsPerPage
      return this.filteredPosts.slice(start, end)
    },
    visiblePages() {
      const pages = []
      const total = this.totalPages
      const current = this.currentPage
      
      if (total <= 5) {
        for (let i = 1; i <= total; i++) {
          pages.push(i)
        }
      } else {
        if (current <= 3) {
          for (let i = 1; i <= 5; i++) {
            pages.push(i)
          }
        } else if (current >= total - 2) {
          for (let i = total - 4; i <= total; i++) {
            pages.push(i)
          }
        } else {
          for (let i = current - 2; i <= current + 2; i++) {
            pages.push(i)
          }
        }
      }
      
      return pages
    }
  },
  mounted() {
    this.loadBlogData()
  },
  methods: {
    async loadBlogData() {
      try {
        this.isLoading = true
        
        // 调用API获取博客数据
        const response = await fetch('http://localhost:3001/api/blog')
        
        if (!response.ok) {
          throw new Error(`HTTP error! status: ${response.status}`)
        }
        
        const result = await response.json()
        
        if (result.success && result.data) {
          // 更新页面数据
          this.pageInfo = result.data.pageInfo || {}
          this.categories = result.data.categories || []
          this.sortOptions = result.data.sortOptions || []
          this.posts = result.data.posts || []
          
          // 初始化筛选结果
          this.filteredPosts = [...this.posts]
          this.sortPosts()
        } else {
          throw new Error(result.message || 'API返回数据格式错误')
        }
        
      } catch (error) {
        console.error('加载博客数据失败:', error)
        this.apiError = error.message
        
        // 设置默认数据作为后备
        this.setDefaultData()
      } finally {
        this.isLoading = false
      }
    },
    
    setDefaultData() {
      // 后备数据，防止API调用失败
      this.pageInfo = {
        title: '博客文章',
        subtitle: '分享技术心得、生活感悟和成长历程'
      }
      
      this.categories = [
        { name: '所有分类', value: '' },
        { name: '技术分享', value: '技术分享' },
        { name: '生活随笔', value: '生活随笔' },
        { name: '学习笔记', value: '学习笔记' },
        { name: '项目经验', value: '项目经验' }
      ]
      
      this.sortOptions = [
        { name: '按日期排序', value: 'date' },
        { name: '按阅读量排序', value: 'views' },
        { name: '按标题排序', value: 'title' }
      ]
      
      this.posts = [
        {
          id: 1,
          title: 'Vue 3 组合式API详解',
          excerpt: '深入了解Vue 3的组合式API，如何使用setup函数和响应式API来构建更好的Vue应用...',
          image: 'background.jpg',
          category: '技术分享',
          tags: ['Vue', 'JavaScript', '前端'],
          date: '2025-09-15',
          views: 1234
        }
      ]
      
      this.filteredPosts = [...this.posts]
      this.sortPosts()
    },
    
    getImageUrl(imageName) {
      // 将JSON中的图片名转换为实际的图片路径
      try {
        return require(`@/assets/${imageName}`)
      } catch (error) {
        console.warn('图片加载失败:', imageName)
        return require('@/assets/background.jpg') // 默认图片
      }
    },
    
    filterPosts() {
      this.filteredPosts = this.posts.filter(post => {
        const matchKeyword = !this.searchKeyword || 
          post.title.toLowerCase().includes(this.searchKeyword.toLowerCase()) ||
          post.excerpt.toLowerCase().includes(this.searchKeyword.toLowerCase()) ||
          post.tags.some(tag => tag.toLowerCase().includes(this.searchKeyword.toLowerCase()))
        
        const matchCategory = !this.selectedCategory || post.category === this.selectedCategory
        
        return matchKeyword && matchCategory
      })
      
      this.sortPosts()
      this.currentPage = 1
    },
    
    sortPosts() {
      this.filteredPosts.sort((a, b) => {
        switch (this.sortBy) {
          case 'date':
            return new Date(b.date) - new Date(a.date)
          case 'views':
            return b.views - a.views
          case 'title':
            return a.title.localeCompare(b.title)
          default:
            return 0
        }
      })
    },
    
    changePage(page) {
      if (page >= 1 && page <= this.totalPages) {
        this.currentPage = page
        window.scrollTo({ top: 0, behavior: 'smooth' })
      }
    },
    
    clearFilters() {
      this.searchKeyword = ''
      this.selectedCategory = ''
      this.sortBy = 'date'
      this.currentPage = 1
      this.filterPosts()
    },
    
    getCategoryColor(category) {
      const colors = {
        '技术分享': 'bg-primary',
        '生活随笔': 'bg-success',
        '学习笔记': 'bg-warning',
        '项目经验': 'bg-info'
      }
      return colors[category] || 'bg-secondary'
    },
    
    formatDate(date) {
      return new Date(date).toLocaleDateString('zh-CN')
    }
  }
}
</script>

<style scoped>
.card {
  transition: all 0.3s ease;
}

.card:hover {
  transform: translateY(-10px);
  box-shadow: 0 15px 35px rgba(0,0,0,0.15) !important;
}

.post-meta {
  border-top: 1px solid #f0f0f0;
  padding-top: 1rem;
}

.page-link {
  cursor: pointer;
}

.badge {
  font-size: 0.75rem;
}

.form-control:focus,
.form-select:focus {
  border-color: #86b7fe;
  box-shadow: 0 0 0 0.25rem rgba(13, 110, 253, 0.25);
}

.input-group-text {
  color: #6c757d;
}
</style>
